// pages/cart/index.js
import { getSetting, chooseAddress, openSetting, showModal, showToast, requestPayment } from "../../utils/asyncWc.js";
import { request } from "../../request/index";

Page({
  data: {
    address: {},
    cart: [],
    totalPrice: 0,
    totalNum: 0
  },
  onShow() {
    // 获取缓存中的收货地址信息
    const address = wx.getStorageSync("address")
    // 获取缓存中的购物车数据
    let cart = wx.getStorageSync("cart") || []
    // 过滤后的购物车数据
    cart = cart.filter(v => v.checked)

    let totalPrice = 0
    let totalNum = 0
    cart.forEach(v => {
      totalPrice += v.num * v.goods_price
      totalNum += v.num
    })
    // 给data赋值
    this.setData({
      cart,
      totalPrice,
      totalNum,
      address,
    })
  },
  // 点击 支付
  async handlePrderPay() {
    try {
      // 判读缓存中有没有token
      const token = wx.getStorageSync("token")
      if (!token) {
        wx.navigateTo({
          url: '/pages/auth/index'
        })
        return
      }
      // 准备创建订单
      const header = { Authorization: token }
      const order_price = this.data.totalNum
      const consignee_addr = this.data.address.all
      const cart = this.data.cart
      let goods = []
      cart.forEach(v => goods.push({
        goods_id: v.goods_id,
        goods_number: v.num,
        goods_price: v.goods_price
      }))
      const orderParams = { order_price, consignee_addr, goods }
      // 发送请求 获取订单
      const { order_number } = await request({ url: "/my/orders/create", method: "post", data: orderParams, header })
      // 准备发起预支付的接口
      const { pay } = await request({ url: "/my/orders/req_unifiedorder", method: "post", data: { order_number }, header })
      // 发起 微信支付
      await requestPayment(pay)
      const res = await request({ url: "/my/orders/chkOrder", method: "post", data: { order_number }, header })
      
      await showToast({title: "支付成功！"})
      // 删除缓存中 被支付的商品
      let newCart = wx.getStorageSync("cart")
      newCart = newCart.filter(v=>!v.checked)
      wx.setStorageSync("cart", newCart)
      // 支付成功 跳转到订单页面
      wx.navigateTo({
        url: '/pages/order/index'
      })
    } catch (error) {
      await showToast({title: "支付失败！"})
      console.log(error)
    }
  }
})
